import {reqUserInfo,reqPhoneCode,reqToken} from '@/api'
const state = {
    userInfo:{},
    code:'',
    token:localStorage.getItem('TOKEN_KEY')
}

const mutations = {
    //保存用户信息
    RECEIVED_USERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    //修改验证码
    RECEIVED_CODE(state,code){
        state.code = code
    },
    //获取token
    RECEIVED_TOKEN(state,token){
        state.token = token
    },
    //重置token
    RESET_TOKEN(state){
        state.token = ''
    },
    RESET_USERINFO(state){
        state.userInfo = {},
        state.token = ''
    }
}

const actions = {
    //获取用户信息
    async getUserInfo({commit}){
        const userInfoData = await reqUserInfo()
        // console.log(phone,password)
        if(userInfoData.code === 200){
            commit('RECEIVED_USERINFO',userInfoData.data) 
            return userInfoData.data.name
        }else{
            return Promise.reject(new Error('failed'))
        }
    },
    //获取验证码
    async getCode({commit}){
        const codeData = await reqPhoneCode()
        if(codeData.code === 200){
            commit('RECEIVED_CODE',codeData.data)
            return codeData.data
        }else{
            return '获取验证码失败'
        }
    },
    //获取token
    async getToken({commit},{phone,password}){
        const result = await reqToken(phone,password)
        if(result.code === 200){
            commit('RECEIVED_TOKEN',result.result.token)
            localStorage.setItem('TOKEN_KEY',result.result.token)
            return '获取token成功'
        }else{
            return '获取token失败'
        }
    },
    //重置token
    async resetToken({commit}){
        commit('RESET_TOKEN')
    },
    // 清空token
    async logout({commit}){
        commit('RESET_USERINFO'),
        localStorage.removeItem('TOKEN_KEY')
        return 'ok'
    }
  }

const getters = {

}

export default {
  state,
  mutations,
  actions,
  getters
}